
import { defineStore } from 'pinia'
import type { Chat, Message } from '@/types'
import { ref } from 'vue'

export const useChatStore = defineStore('chat', () => {
  const chats = ref<Chat[]>([
    {
      id: '1',
      type: 'private',
      name: '张三',
      avatar: '/images/avatars/avatar1.jpg',
      lastMessage: {
        id: '1',
        chatId: '1',
        senderId: '1',
        content: '你好，在吗？',
        type: 'text',
        timestamp: Date.now() - 3600000,
        status: 'read'
      },
      unreadCount: 2,
      members: ['1', '2'],
      isTop: true
    },
    {
      id: '2',
      type: 'group',
      name: '技术交流群',
      avatar: '/images/avatars/group1.jpg',
      lastMessage: {
        id: '2',
        chatId: '2',
        senderId: '3',
        content: '今晚8点开会',
        type: 'text',
        timestamp: Date.now() - 7200000,
        status: 'delivered'
      },
      unreadCount: 5,
      members: ['1', '2', '3', '4', '5']
    }
  ])

  const currentChat = ref<Chat | null>(null)
  const messages = ref<Message[]>([])
  const isTyping = ref(false)

  const setCurrentChat = (chat: Chat) => {
    currentChat.value = chat
    // 清空未读消息
    const chatIndex = chats.value.findIndex(c => c.id === chat.id)
    if (chatIndex !== -1) {
      chats.value[chatIndex].unreadCount = 0
    }
  }

  const addMessage = (message: Message) => {
    messages.value.push(message)
    // 更新最后一条消息
    const chatIndex = chats.value.findIndex(c => c.id === message.chatId)
    if (chatIndex !== -1) {
      chats.value[chatIndex].lastMessage = message
    }
  }

  const updateMessageStatus = (messageId: string, status: Message['status']) => {
    const messageIndex = messages.value.findIndex(m => m.id === messageId)
    if (messageIndex !== -1) {
      messages.value[messageIndex].status = status
    }
  }

  const setTyping = (typing: boolean) => {
    isTyping.value = typing
  }

  return {
    chats,
    currentChat,
    messages,
    isTyping,
    setCurrentChat,
    addMessage,
    updateMessageStatus,
    setTyping
  }
})
